package com.atguigu.gmall.common.exception;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author:lyd
 * @Date:2023/8/22 19:54
 * @Version:1.0
 * @Description 编写全局处理异常类，这个类负责收集所有controller中出现的异常
 **/
@Component
//@ResponseBody
//@ControllerAdvice //收集所有controller出现的异常
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 统一构造失败响应
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(GmallException.class)//业务期间所有的异常都设置为GmallException形式抛出
    public Result handlerException(GmallException exception) {
        Result<Object> result = new Result<>();
        result.setCode(exception.getCode());
        result.setMessage(exception.getMessage());
        return result;
    }


    /**
     * 处理业务之间所有的异常
     * @param throwable
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public Result handlerException(Throwable throwable) {
        Result<Object> result = new Result<>();
        result.setCode(500);
        result.setMessage(throwable.getMessage());
        throwable.printStackTrace();
        return result;
    }
}
